package cloudInformation.customer;

import cn.hutool.core.util.IdUtil;
import io.minio.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
@Slf4j
public class MinioService {

    private final MinioClient minioClient;

    @Value("${minio.newsbBucketName}")
    private String bucketName;

    public MinioService(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问URL
     */
    public String uploadFile(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        String sufix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String simpleUUID = IdUtil.simpleUUID()+sufix;
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(simpleUUID)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        return  simpleUUID;
    }

    /**
     * 下载文件
     * @param fileName 文件名
     * @return 文件流
     */
    public InputStream downloadFile(String fileName) throws Exception {
        return minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .build());
    }

    /**
     * 删除文件
     * @param fileName 文件名
     */
    public void deleteFile(String fileName) throws Exception {
        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .build());
    }

    /**
     * 获取文件url
     * @param fileName 文件名
     * @return 返回 字符串 Url
     * @throws Exception
     */
    public String getFileUrl(String fileName) throws Exception {
        String url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                //.expiry(3, TimeUnit.MINUTES) //指定有效期为3分钟，地址生成3分钟后即失效无法在访问文件
                .method(Method.GET) //设置访问文件url的请求方式为get
                .build()
        );
        System.out.println(url);
        return url;
    }

}
